<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="由于数据监管的要求，公司的数据必须放在不同的国家，蛋疼的是第一次感受到了光速的“慢”。数据存储于，印度，美国等，每一次查询都有200ms的延迟。而且这延迟是由于光速的限制，是物理限制，买再大的带宽也没有用。 只好自己写了一个主动缓存的方案。 挺有意思的, 可以参考参考~">
<meta property="og:type" content="article">
<meta property="og:title" content="主动缓存">
<meta property="og:url" content="https://guodh.gitee.io/blog/2019/07/28/2019/%E4%B8%BB%E5%8A%A8%E7%BC%93%E5%AD%98/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="由于数据监管的要求，公司的数据必须放在不同的国家，蛋疼的是第一次感受到了光速的“慢”。数据存储于，印度，美国等，每一次查询都有200ms的延迟。而且这延迟是由于光速的限制，是物理限制，买再大的带宽也没有用。 只好自己写了一个主动缓存的方案。 挺有意思的, 可以参考参考~">
<meta property="og:locale">
<meta property="og:image" content="https://guodh.gitee.io/Cache.png">
<meta property="article:published_time" content="2019-07-28T04:55:56.000Z">
<meta property="article:modified_time" content="2019-08-20T09:59:40.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://guodh.gitee.io/Cache.png">

<link rel="canonical" href="https://guodh.gitee.io/blog/2019/07/28/2019/%E4%B8%BB%E5%8A%A8%E7%BC%93%E5%AD%98/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>主动缓存 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2019/07/28/2019/%E4%B8%BB%E5%8A%A8%E7%BC%93%E5%AD%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          主动缓存
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2019-07-28 12:55:56" itemprop="dateCreated datePublished" datetime="2019-07-28T12:55:56+08:00">2019-07-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2019-08-20 17:59:40" itemprop="dateModified" datetime="2019-08-20T17:59:40+08:00">2019-08-20</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>由于数据监管的要求，公司的数据必须放在不同的国家，蛋疼的是第一次感受到了光速的“慢”。数据存储于，印度，美国等，每一次查询都有200ms的延迟。而且这延迟是由于光速的限制，是物理限制，买再大的带宽也没有用。</p>
<p>只好自己写了一个主动缓存的方案。</p>
<p>挺有意思的, 可以参考参考~</p>
<a id="more"></a>

<img src="/Cache.png" width="100%" height="100%" alt="交付流程"/>

<p>简单的讲就是，用户读取的永远是缓存中的数据，只是通过定时任务来触发任务的更新。对于一些需要立即展示的数据，需要增加下MQ的消息监听，刷新数据就行。</p>
<h2 id="消息监听"><a href="#消息监听" class="headerlink" title="消息监听"></a>消息监听</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserLoginListener</span> <span class="keyword">implements</span> <span class="title">MessageListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> RegisterUserService registerUserService;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Action <span class="title">consume</span><span class="params">(Message message, ConsumeContext context)</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">        UserMessage userMessage = (UserMessage) defaultJDKMessageSeri.deserialize(message.getBody());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;LOGIN&quot;</span>.equals(message.getTag())) &#123;</span><br><span class="line">            registerUserService.login(userMessage.getClientId());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;LOGOUT&quot;</span>.equals(message.getTag())) &#123;</span><br><span class="line">            registerUserService.loginOut(userMessage.getClientId());</span><br><span class="line">        &#125;            </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="定时任务"><a href="#定时任务" class="headerlink" title="定时任务"></a>定时任务</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RegisterUserService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 由于需要使用scan功能，避免scan过多内容，使用redis的hashmap</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> CacheActivityHandlerService activityHandlerService;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long tokenExpireTime = <span class="number">60</span> * <span class="number">60</span> * <span class="number">2L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(</span><br><span class="line">        <span class="keyword">new</span> BasicThreadFactory</span><br><span class="line">            .Builder()</span><br><span class="line">            .namingPattern(<span class="string">&quot;register-User-Scheduled-%d&quot;</span>)</span><br><span class="line">            .build()</span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String USER_LOGIN_KEY = <span class="string">&quot;business:payment:user_login_clientId&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     *  线程可支持：</span></span><br><span class="line"><span class="comment">     *  时间间隔 * 线程数 / 每次 job 大概的耗时</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     *  20s * 4(线程) / 1.5s = 53 个 用户 2小时在线</span></span><br><span class="line"><span class="comment">     *  20s * 8(线程) / 1.5s = 106 个用户 2小时在线</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="comment">// 每次调度会有一堆的任务被塞进来，而且都是IO类型的任务</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> ExecutorService activityCacheParallelExecutor = <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">        <span class="number">4</span>,   <span class="comment">// 避免把其他应用并发挂了</span></span><br><span class="line">        <span class="number">8</span>,  <span class="comment">// 极端情况开多一点线程</span></span><br><span class="line">        <span class="number">0L</span>,</span><br><span class="line">        TimeUnit.MILLISECONDS,</span><br><span class="line">        <span class="keyword">new</span> LinkedBlockingQueue&lt;&gt;(<span class="number">512</span>), <span class="keyword">new</span> BasicThreadFactory.Builder().namingPattern(<span class="string">&quot;activity-Cache-Thread-%d&quot;</span>).build());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        scheduledExecutorService.scheduleAtFixedRate(() -&gt; &#123;</span><br><span class="line"></span><br><span class="line">            StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">            sb.append(<span class="string">&quot;在线用户clientId：&quot;</span>);</span><br><span class="line"></span><br><span class="line">            Cursor&lt;Map.Entry&lt;Object,Object&gt;&gt; cursor = redisTemplate.opsForHash().scan(USER_LOGIN_KEY, ScanOptions.NONE);</span><br><span class="line">            <span class="keyword">while</span> (cursor.hasNext())&#123;</span><br><span class="line">                Map.Entry&lt;Object,Object&gt; entry = cursor.next();</span><br><span class="line">                String clientId = (String) entry.getKey();</span><br><span class="line">                Long time = (Long) entry.getValue();</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (StringUtils.isEmpty(clientId)) &#123;</span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (time == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.loginOut(clientId);</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> ((System.currentTimeMillis() - time) / <span class="number">1000</span> &gt; tokenExpireTime) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.loginOut(clientId);</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    activityCacheParallelExecutor.submit(() -&gt; &#123;</span><br><span class="line">                        ActivityRequest activityRequest = <span class="keyword">new</span> ActivityRequest();</span><br><span class="line">                        activityRequest.setClientId(clientId);</span><br><span class="line">                        activityRequest.setPageSize(<span class="number">10</span>);</span><br><span class="line">                        activityRequest.setPageNo(<span class="number">1</span>);</span><br><span class="line">                        activityHandlerService.putCacheActivity(activityRequest);</span><br><span class="line">                    &#125;);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                    <span class="comment">// 可能队列满了，抛出错误</span></span><br><span class="line">                    log.error(<span class="string">&quot;error happen when submit job, clientIdLoginTimeMap:&#123;&#125;&quot;</span>, sb, e);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                sb.append(<span class="string">&quot;; &quot;</span>);</span><br><span class="line">                sb.append(clientId);</span><br><span class="line">                sb.append(<span class="string">&quot;-loginTime:&quot;</span>);</span><br><span class="line">                sb.append(time);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 从 15s 改成了 20s，减少应用压力</span></span><br><span class="line">        &#125;, <span class="number">0</span>, <span class="number">20</span>, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">login</span><span class="params">(String clientId)</span> </span>&#123;</span><br><span class="line">        redisTemplate.opsForHash().put(USER_LOGIN_KEY, clientId, System.currentTimeMillis());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ActivityRequest activityRequest = <span class="keyword">new</span> ActivityRequest();</span><br><span class="line">            activityRequest.setClientId(clientId);</span><br><span class="line">            activityRequest.setPageSize(<span class="number">10</span>);</span><br><span class="line">            activityRequest.setPageNo(<span class="number">1</span>);</span><br><span class="line">            activityHandlerService.putCacheActivity(activityRequest);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">&quot;error happen when login, clientId:&#123;&#125;&quot;</span>, clientId, e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loginOut</span><span class="params">(String clientId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ActivityRequest activityRequest = <span class="keyword">new</span> ActivityRequest();</span><br><span class="line">            activityRequest.setClientId(clientId);</span><br><span class="line">            activityRequest.setPageSize(<span class="number">10</span>);</span><br><span class="line">            activityRequest.setPageNo(<span class="number">1</span>);</span><br><span class="line">            activityHandlerService.deleteCacheActivity(activityRequest);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">&quot;error happen when loginOut, clientId:&#123;&#125;&quot;</span>, clientId, e);</span><br><span class="line">        &#125;</span><br><span class="line">        redisTemplate.opsForHash().delete(USER_LOGIN_KEY, clientId);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h2 id="用户查询，SpringCache缓存"><a href="#用户查询，SpringCache缓存" class="headerlink" title="用户查询，SpringCache缓存"></a>用户查询，SpringCache缓存</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Cacheable(cacheNames = &quot;activity&quot;</span></span><br><span class="line"><span class="meta">    , key = &quot;#activityRequest.clientId + &#x27;_&#x27; + #activityRequest.pageSize + &#x27;_&#x27; + #activityRequest.pageNo&quot;</span></span><br><span class="line"><span class="meta">    , condition = &quot;#activityRequest.pageNo &lt;= 2&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;UserActivityDTO&gt; <span class="title">cacheActivity</span><span class="params">(ActivityRequest activityRequest)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">&quot;cacheActivity, activityRequest:&#123;&#125;&quot;</span>, activityRequest);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.queryActivity(activityRequest);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@CachePut(cacheNames = &quot;activity&quot;</span></span><br><span class="line"><span class="meta">    , key = &quot;#activityRequest.clientId + &#x27;_&#x27; + #activityRequest.pageSize + &#x27;_&#x27; + #activityRequest.pageNo&quot;</span></span><br><span class="line"><span class="meta">    , condition = &quot;#activityRequest.pageNo &lt;= 2&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;UserActivityDTO&gt; <span class="title">putCacheActivity</span><span class="params">(ActivityRequest activityRequest)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">&quot;putCacheActivity, activityRequest:&#123;&#125;&quot;</span>, activityRequest);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.queryActivity(activityRequest);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@CacheEvict(cacheNames = &quot;activity&quot;</span></span><br><span class="line"><span class="meta">    , key = &quot;#activityRequest.clientId + &#x27;_&#x27; + #activityRequest.pageSize + &#x27;_&#x27; + #activityRequest.pageNo&quot;</span></span><br><span class="line"><span class="meta">    , condition = &quot;#activityRequest.pageNo &lt;= 2&quot;,</span></span><br><span class="line"><span class="meta">    beforeInvocation = true)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;UserActivityDTO&gt; <span class="title">deleteCacheActivity</span><span class="params">(ActivityRequest activityRequest)</span> </span>&#123;</span><br><span class="line">    log.info(<span class="string">&quot;deleteCacheActivity, activityRequest:&#123;&#125;&quot;</span>, activityRequest);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>PS: 当事务中涉及缓存操作的时候可以这么搞。这样就可以做一个通用的query方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    String key = clientId;</span><br><span class="line">    query(key);</span><br><span class="line">    threadLocal.set(key);</span><br><span class="line">&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">    log.info();</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">       String key = threadLocal.get();</span><br><span class="line">       redis.delete(key);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E6%8A%80%E6%9C%AF/" rel="tag"># 技术</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2019/07/07/2019/K8S-1/" rel="prev" title="K8S连载(一)">
      <i class="fa fa-chevron-left"></i> K8S连载(一)
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2019/08/30/2019/%E9%93%B6%E8%A1%8C%E4%BD%93%E7%B3%BB/" rel="next" title="银行体系">
      银行体系 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B6%88%E6%81%AF%E7%9B%91%E5%90%AC"><span class="nav-number">1.</span> <span class="nav-text">消息监听</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1"><span class="nav-number">2.</span> <span class="nav-text">定时任务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%A8%E6%88%B7%E6%9F%A5%E8%AF%A2%EF%BC%8CSpringCache%E7%BC%93%E5%AD%98"><span class="nav-number">3.</span> <span class="nav-text">用户查询，SpringCache缓存</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
